package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    //发送短信验证码
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody Map<String, String> map, HttpSession session) {
        //获取手机号
        String phone = map.get("phone");
        //判断redis中是否存在这个KEY,如果存在说明验证码未过期
        if(redisTemplate.hasKey(phone)){
            return R.error("验证码还未失效，不允许重复操作");
        }
        //随机生成验证码
        // String code = ValidateCodeUtils.generateValidateCode(4).toString();
        String code = "1234";
        //把验证码设置到redis中
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

        //调用阿里云发送验证码
        //SMSUtils.sendMessage("ABC商城", "SMS_208640979", phone, code);

        //保存验证码，和用户输入的验证码进行匹配
        // session.setAttribute(phone, code);
        //返回验证码正确输入信息
        return R.success("发送验证成功");

    }

    //移动端登录功能
    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String, String> map, HttpSession session) {
        //1.获取用户和验证码
        String phone = map.get("phone");
        String code = map.get("code");
        //2.获取Session中的验证码
        // String codeInSession = (String) session.getAttribute(phone);
        String redisCode = (String) redisTemplate.opsForValue().get(phone);
        //比对验证码
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //不允许登录
            return R.error("验证码错误");
        }
        //判断用户是否是新用户，根据手机号查询数据库
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, phone);
        User user = userService.getOne(lqw);
        if (user == null) {
            //新用户添加到数据库，进行（注册）
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            user.setName("孙" + user.getPhone());
            userService.save(user);
        } else {
            Integer status = user.getStatus();
            if (status == 0) {
                //用户被禁用
                return R.error("用户已被禁用");
            }
        }
        //将session中的验证码移除
        // session.removeAttribute(phone);
        //将redis中的验证码移除掉
        redisTemplate.delete(phone);
        //将用户的ID存入session中
        session.setAttribute("user", user.getId());

        return R.success("登录成功");
    }

    //退出登录
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("成功退出");
    }

}
